import calendar as cal
import datetime
import math
import os
import pickle
import random
import sys
import time as t

systime = datetime.datetime.now()


class Sysinfo:
    def __init__(self, devm, applist, osver):
        self.devm = devm
        self.applist = applist
        self.osver = osver


Info = None
pyosdict = None


def selftest():
    print("process id:", os.getpid())
    print("parent pid:", os.getppid())
    print("host os:", sys.platform, os.name)
    print("running at:", os.getcwd())
    if not os.path.exists(os.getcwd() + "\Logs"):
        os.mkdir(os.getcwd() + r"\Logs")
    if not os.path.exists(os.getcwd() + "\Sysinfo.data"):
        infowrite()
        inforead()
    else:
        inforead()
    log_appstart("PyOSMain")
    welcome()
    main()


def welcome():
    print("欢迎使用PyOS")
    print("输入help查看帮助")


def help():
    for i in Info.applist:
        print(i, end=" ")
        print(translator(i))
    main()


def translator(before):
    global pyosdict
    pyosdict = {"calc": "计算器", "calendar": "日历", "time": "时间", "devmode": "开发者模式", "calcpi": "（假）性能测试"}
    after = pyosdict.get(before)
    return after


def main():
    global Info
    inp = sys_inp("PyOS")
    if inp in Info.applist:
        app_launch(inp)
    else:
        print("应用不存在")
        main()


def app_launch(appname):
    log_appstart(appname)
    eval(appname)()


def tre():
    log_costom("系统时间刷新")
    global systime
    systime = datetime.datetime.now()


def sys_inp(appname):
    inp = ""
    inp = input(appname + ">>>")
    return inp


def calendar():
    inp = ""
    log_appstart("calendar")
    tre()
    print(cal.month(systime.year, systime.month, w=3, l=3))
    print("输入yr查看年视图,exit退出")
    while True:
        inp = sys_inp("calendar")
        if inp == "yr":
            calendar_yr()
        elif inp == "exit":
            print("你已退出日历")
            main()
        else:
            print("输入无效")


def calendar_yr():
    print(cal.calendar(systime.year))
    print("输入mo查看月视图,exit退出")
    while True:
        inp = sys_inp("calendar")
        if inp == "mo":
            calendar()
        elif inp == "exit":
            print("你已退出日历")
            main()
        else:
            print("输入无效")


def calc():
    print("calc计算器v0.9pre")
    print("运算符号等同Python,输入exit退出")
    while True:
        inp = sys_inp("calc")
        if inp == "exit":
            print('你已退出计算器')
            main()
        else:
            try:
                print("={}".format(eval(inp)))
            except NameError:
                print("请输入数学算式")
                calc()


def time():
    tre()
    week_dict = {"Mon": "星期一", "Tue": "星期二", "Wed": "星期三", "Thu": "星期四", "Fri": "星期五", "Sat": "星期六", "Sun": "星期天"}
    week = week_dict.get(systime.strftime("%a"))
    print("现在是{}年{}月{}日{}{}".format(systime.year, systime.month, systime.day, systime.strftime("%X"), week))
    main()


def devmode():
    global Info
    Info.devm = not Info.devm
    print("开发者模式启用现为{}".format(str(Info.devm)))
    inforew()
    main()


def log_appstart(appname):
    tre()
    log = appname + "于" + systime.strftime("%X") + "启动"
    sys_logwrite(log)


def log_costom(text):
    log = text + "于" + systime.strftime("%X")
    sys_logwrite(log)


def sys_logwrite(logname):
    global Info
    if Info.devm:
        print(logname)
    logf = open(os.getcwd() + "\Logs\\" + "PyOSLog" + systime.strftime("%y-%m-%d") + ".log", "a")
    logf.write(logname)
    logf.write("\n")
    logf.close()


def rsleep():
    t.sleep(random.random())


def rpb():
    x = 50
    for i in range(x + 1):
        a = i * "*"
        b = (x - i) * ">"
        c = 100 * (i / x)
        print("\r{:^3.0f}%[{}->{}]".format(c, a, b), end="")
        rsleep()
    main()


def calcpi():
    log_appstart("性能测试")
    darts = pow(2, 25)
    hits = 0.0
    tm = t.time()
    for i in range(1, darts + 1):
        x, y = random.random(), random.random()
        dist = math.sqrt(pow(x, 2) + pow(y, 2))
        if dist <= 1.0:
            hits += 1
    pi = 4 * (hits / darts)
    tm = t.time() - tm
    score = 1000 * tm
    print("Score:{:d}".format(int(score)))
    log_costom("性能测试被进行分数为{}".format(int(score)))
    main()


def infowrite():
    global Info
    Info = Sysinfo(False, ["calc", "calendar", "time", "devmode", "calcpi", "rpb", "help"], "v0.7alpha")
    with open("Sysinfo.data", "wb") as inf:
        pickle.dump(Info, inf)
    log_costom("data文件创建")


def inforew():
    global Info
    with open("Sysinfo.data", "wb") as inf:
        pickle.dump(Info, inf)
    log_costom("data文件更改")


def inforead():
    inf = open("Sysinfo.data", "rb")
    data = inf.read()
    global Info
    Info = pickle.loads(data)
    log_costom("data文件读取")
    inf.close()


selftest()
